<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 用户列表信息 -->
    <el-card>
      <!-- 搜索和添加用户按钮模块 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            v-model="queryData.query"
            @clear="getUserList"
            placeholder="请输入搜索内容"
            class="input-with-select"
            clearable
          >
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户信息展示模块 -->
      <el-row>
        <el-table :data="userList" border :stripe="true">
          <!-- 设置type属性为index即可显示从 1 开始的索引号 -->
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <!-- 插槽的使用,item.row会返回当前行的数据 -->
            <template slot-scope="item">
              <el-switch
                v-model="item.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="setStatus(item.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <!-- template里面写的是自定义组件 -->
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button
                @click="editDialog(scope.row.id)"
                size="mini"
                type="primary"
                icon="el-icon-edit"
              ></el-button>
              <!-- 删除按钮 -->
              <el-button
                @click="delUser(scope.row.id)"
                size="mini"
                type="danger"
                icon="el-icon-delete"
              ></el-button>
              <!-- 分配角色 -->
              <el-tooltip
                :enterable="false"
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
              >
                <el-button @click='showSetRoleDialog(scope.row)' size="mini" type="warning" icon="el-icon-setting"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页功能 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryData.pagenum"
          :page-sizes="[2, 4, 8, 10]"
          :page-size="queryData.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-row>
    </el-card>

    <!-- 添加用户按钮对话框 -->
    <el-dialog @close="resetForm" title="添加用户" :visible.sync="addDialogVisible" width="50%">
      <!-- 对话框内容区,ref是表单 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- prop中的字段和model中的字段需要保持一致,方便和接口发送请求 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="checkForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户按钮对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%">
      <el-form
        @close="resetEditDialog"
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名称">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserSub">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      >
      <p>当前的用户：{{userInfo.username}}</p>
      <p>当前的角色：{{userInfo.role_name}}</p>
      <div>
        分配角色:
        <el-select v-model="activeOpt" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleSub">确 定</el-button>
      </span>
    </el-dialog>  
  </div>
</template>

<script>
export default {
  data() {
    const checkEmail = (r, v, cb) => {
      const regEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      if (regEmail.test(v)) {
        return cb();
      }
      cb(new Error("邮箱格式不正确!"));
    };
    const checkMobile = (r, v, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(v)) {
        return cb();
      }
      cb(new Error("手机号码格式不正确!"));
    };
    return {
      queryData: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制编辑用户对话框的显示与隐藏
      editDialogVisible: false,
      // 保存修改用户的信息
      editForm: {},
      // 添加用户信息
      addForm: {
        username: "test",
        password: "123",
        email: "lhs@123.com",
        mobile: 18888888888
      },
      // 添加用户信息对话框校验规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 2, max: 7, message: "长度在 2 到 7 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 8, message: "长度在 6 到 8 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 编辑用户信息对话框校验规则
      editRules: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible:false,
      // 保存分配角色对话框重用户名和角色信息
      userInfo:{},
      // 保存所有的角色信息
      rolesList:[],
      // 用于保存选择当前角色的id
      activeOpt:''
    };
  },

  methods: {
    async getUserList() {
      var res = await this.axios.get("/users", {
        params: this.queryData
      });
      if (res.meta.status != 200)
        return this.$mg.error("获取用户,列表失败,请查看代码");
      this.userList = res.data.users;
      this.total = res.data.total;
      //   console.log(this.userList);
    },
    // 修改用户状态
    async setStatus(row) {
      //   console.log(row);
      var res = await this.axios.put(`users/${row.id}/state/${row.mg_state}`);
      //   console.log(res);
      if (res.meta.status == 200) {
        this.$mg.success("修改用户状态成功");
      } else {
        this.$mg.error("修改用户状态失败");
      }
    },
    // 每页多少条发生变幻时触发
    handleSizeChange(val) {
      //   console.log(val);
      this.queryData.pagesize = val;
      this.getUserList();
    },
    // 修改当前页码时触发
    handleCurrentChange(val) {
      //   console.log(val);
      this.queryData.pagenum = val;
      this.getUserList();
    },
    // 对话框关闭的时候重置表单的输入数据
    resetForm() {
      console.log(this.$refs);
      this.$refs.addFormRef.resetFields();
    },

    // 给对话框的确定按钮添加点击事件,验证表单
    checkForm() {
      this.$refs.addFormRef.validate(async flag => {
        if (!flag) return;
        console.log("校验成功!");
        const res = await this.axios.post("users", this.addForm);
        // console.log(res);
        if (res.meta.status == 201) {
          this.$mg.success(res.meta.msg);
          this.addDialogVisible = false;
          this.getUserList();
        } else {
          this.$mg.error(res.meta.msg);
        }
      });
    },
    // 编辑用户信息
    async editDialog(id) {
      // console.log(id);
      const res = await this.axios.get("users/" + id);
      // console.log(res);
      if (res.meta.status == 200) {
        this.editForm = res.data;
      }
      this.editDialogVisible = true;
    },
    // 重置编辑对话框
    resetEditDialog() {
      this.$refs.editFormRef.resetFields();
    },
    // 给编辑对话框中的确定按钮添加点击事件
    editUserSub() {
      this.$refs.editFormRef.validate(async flag => {
        if (!flag) return;
        console.log("编辑用户成功!");
        const res = await this.axios.put("users/" + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        });
        console.log(res);
        if (res.meta.status == 200) {
          this.editDialogVisible = false;
          this.getUserList();
          this.$mg.success(res.meta.msg);
        } else {
          this.$mg.error(res.meta.msg);
        }
      });
    },
    // 删除用户信息
    delUser(id) {
      this.$cfm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const res = await this.axios.delete(`users/${id}`);
          if (res.meta.status == 200) {
            this.$mg.success(res.meta.msg);
            this.getUserList();
          } else {
            this.$mg.error(res.meta.msg);
          }
        })
        .catch(() => {
          this.$mg.info("取消删除");
        });
    },

    // 显示分配角色对话框
    async showSetRoleDialog(row){
      this.userInfo=row;
      this.setRoleDialogVisible=true;
      const res=await this.axios.get('roles');
      
      if(res.meta.status==200){
        this.rolesList=res.data;
      }
      // console.log(this.rolesList);      
    },

    //保存设置当前新角色
    async setRoleSub(){
      // console.log(this.userInfo.id);
      // console.log(this.activeOpt);
      
      if(!this.activeOpt) return this.$mg.info('请选择一个新角色');
      const res=await this.axios.put(`users/${this.userInfo.id}/role`,{
        rid:this.activeOpt
      })
      if(res.meta.status==200){
        this.$mg.success(res.meta.msg);
        this.setRoleDialogVisible=false;
        this.getUserList();
      }
    }

  },
  // dom结构生成之前就执行
  created() {
    this.getUserList();
  }
};
</script>

<style lang='less' scoped>
</style>
